﻿#include "sysmsgcontroller.h"
#include "utils/dictionaryutil.h"

SysMsgController::SysMsgController()
{
    m_pHelper = DbMgr::instance()->getHelper();

    m_mapFunc.insert("/func/message/sys/status",    &SysMsgController::status);     //获取系统消息状态
    m_mapFunc.insert("/func/message/sys/type",      &SysMsgController::type);       //获取系统消息类型
    m_mapFunc.insert("/func/message/sys/datagrid",  &SysMsgController::datagrid);   //获取系统消息列表
    m_mapFunc.insert("/func/message/sys/detail",    &SysMsgController::detail);     //获取系统消息明细
    m_mapFunc.insert("/func/message/sys/save",      &SysMsgController::save);       //保存系统消息
    m_mapFunc.insert("/func/message/sys/delete",    &SysMsgController::del);        //删除系统消息
    m_mapFunc.insert("/func/message/sys/publish",   &SysMsgController::publish);    //发布系统消息

}

void SysMsgController::service(HttpRequest& request, HttpResponse& response)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString access_token = request.getParameter("access_token");
    QString username = JwtUtil::getUsername(access_token);
    if(username == NULL || username.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    SysUser visitUser;
    if(!m_pHelper->selectUserByName(visitUser, username))
    {
        ret.failedMsg(QStringLiteral("用户不存在，操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    QByteArray path = request.getPath().toLower();
    if(m_mapFunc.contains(path))
    {
        pServFunc func = m_mapFunc.value(path);
        (this->*func)(request, response, visitUser);
    }
}



//获取系统消息状态
//http://localhost:9004/func/message/sys/status
//{"code":0,"data":[{"label":"草稿","value":"0"},{"label":"已发布","value":"1"}],"msg":""}
void SysMsgController::status(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));

    QMap<QString, QString> map = DictionaryUtil::instance()->getDictionary("func_sys_message_status");

    QMap<QString, QJsonObject> orderMap;
    foreach (QString key, map.keys()) {
         QJsonObject obj;
         obj.insert("label", key);
         obj.insert("value", map[key]);
         orderMap.insert(map[key], obj);
    }
    QJsonArray dataArray;
    foreach (QString key, orderMap.keys())
        dataArray.append(orderMap[key]);
    ret.setData(dataArray);
    ResponseUtil::replyJson(response, ret);
}

//获取系统消息类型
//http://localhost:9004/func/message/sys/type
//{"code":0,"data":[{"label":"系统消息","value":"0"},{"label":"其他","value":"1"}],"msg":""}
void SysMsgController::type(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));

    QMap<QString, QString> map = DictionaryUtil::instance()->getDictionary("func_sys_message_type");

    QMap<QString, QJsonObject> orderMap;
    foreach (QString key, map.keys()) {
         QJsonObject obj;
         obj.insert("label", key);
         obj.insert("value", map[key]);
         orderMap.insert(map[key], obj);
    }
    QJsonArray dataArray;
    foreach (QString key, orderMap.keys())
        dataArray.append(orderMap[key]);
    ret.setData(dataArray);
    ResponseUtil::replyJson(response, ret);
}

//获取系统消息列表
//http://localhost:9004/func/message/sys/datagrid?page=1&limit=30&field=createDate&order=desc&access_token=?
/*
page: 1
limit: 30
field: createDate
order: desc
access_token: ?
{"code":0,"count":6,"data":[{"content":"dddddddddddd","createDate":1578275160000,"createName":"admin","id":?,"publicTime":1578275165000,"status":"1","title":"sdwdw","type":"系统消息","updateDate":1578275165000,"updateName":"admin","versions":1},{"content":"滴答滴答滴答滴答滴","createDate":1578118180000,"createName":"admin","id":"3b2802231b220b26c8172da799aa9b4e","publicTime":1578118183000,"status":"1","title":"大豆纤维","type":"系统消息","updateDate":1578118183000,"updateName":"admin","versions":1},{"content":"我我呜呜呜呜呜呜呜呜呜呜呜呜","createDate":1578114409000,"createName":"admin","id":"1455b0dbdda17bf15600e11537f33d05","publicTime":1578114412000,"status":"1","title":"点点滴滴","type":"其他","updateDate":1578114412000,"updateName":"admin","versions":1},{"content":"dewdwe","createDate":1576736606000,"createName":"admin","id":"df8d2430ecf69205fda107f18ab0b564","publicTime":1576736618000,"status":"1","title":"deww","type":"系统消息","updateDate":1576736618000,"updateName":"admin","versions":1},{"content":"ferf","createDate":1576726356000,"createName":"admin","id":"5dc6045dd3582faca500ffe48dd5e5ca","publicTime":1576726360000,"status":"1","title":"ef","type":"其他","updateDate":1576726360000,"updateName":"admin","versions":1},{"content":"12月平台正式上线，欢迎体验！","createDate":1576722999000,"createName":"admin","id":"5ef3c695332f680d5675e410ba53d65d","publicTime":1576723002000,"status":"1","title":"平台正式上线啦！","type":"其他","updateDate":1576723002000,"updateName":"admin","versions":2}],"msg":""}
*/
void SysMsgController::datagrid(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{

    int page = 1;
    int limit = 30;
    QString field = "createDate";
    QString order = "desc";
    QString title = "";
    QString type = "";
    QString status = "";

    if(request.getParameterMap().contains("page"))
    {
        page = request.getParameter("page").toInt();
    }
    if(request.getParameterMap().contains("limit"))
    {
        limit = request.getParameter("limit").toInt();
    }
    if(request.getParameterMap().contains("field"))
    {
        field = request.getParameter("field");
    }
    if(request.getParameterMap().contains("order"))
    {
        order = request.getParameter("order");
    }
    if(request.getParameterMap().contains("title"))
    {
        title = request.getParameter("title");
    }
    if(request.getParameterMap().contains("type"))
    {
        type = request.getParameter("type");
    }
    if(request.getParameterMap().contains("status"))
    {
        status = request.getParameter("status");
    }

    QStringList condi;
    if(!title.isEmpty())
        condi << "title like '%" + title + "%'";
    if(!type.isEmpty())
        condi << "type = '%" + type + "%'";
    if(!status.isEmpty())
        condi << "status = '%" + status + "%'";
    QList<SysMessage> msgList;
    int count = 0;
    m_pHelper->getSysMessageList(msgList,  count, page, limit, condi, field, order=="asc");

    QMap<QString, QString> mapStatus = DictionaryUtil::instance()->getDictionary("func_sys_message_status");
    QMap<QString, QString> mapType = DictionaryUtil::instance()->getDictionary("func_sys_message_type");
    QJsonArray dataArray;
    foreach (SysMessage msg, msgList) {
        QJsonObject obj = msg.toJson();
        foreach (QString key, mapType.keys()) {
            if(mapType[key] == msg.getType())
            {
                obj.insert("type",  key);
                break;
            }
        }

         dataArray.append(obj);
    }

    ResultJson ret(0, true, QStringLiteral(""));
    ret.setProp("count", msgList.size());
    ret.setData(dataArray);
    ResponseUtil::replyJson(response, ret);
}

//获取系统消息明细
//http://localhost:9004/demo/func/message/sys/detail?id=
//{"code":0,"data":{"content":"dddddddddddd","status":"已发布","time":"2020-01-06 09:46:05","title":"sdwdw","type":"系统消息"},"msg":""}
void SysMsgController::detail(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral(""));
    QString idParam = request.getParameter("id");

    if(idParam.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    int id = idParam.toInt();

    SysMessage msg;
    msg.setId(id);
    if(!m_pHelper->selectEntityById(&msg))
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    QMap<QString, QString> mapStatus = DictionaryUtil::instance()->getDictionary("func_sys_message_status");
    QMap<QString, QString> mapType = DictionaryUtil::instance()->getDictionary("func_sys_message_type");

    QJsonObject obj = msg.toJson();

    foreach (QString key, mapStatus.keys()) {
        if(mapStatus[key] == msg.getStatus())
        {
            obj.insert("status",  key);
            break;
        }
    }
    foreach (QString key, mapType.keys()) {
        if(mapType[key] == msg.getType())
        {
            obj.insert("type",  key);
            break;
        }
    }

    ret.setData(obj);
    ResponseUtil::replyJson(response, ret);
}

//保存系统消息
//http://localhost:9004/demo/func/message/sys/save
/*
id:
title: ceshui
type: 1
content: cveiwfgwihgiwpgwgwg
access_token:
*/
//{"code":0,"success":true,"msg":"操作成功","data":null}
void SysMsgController::save(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral(""));

    SysMessage msg;
    msg.setTitle(request.getParameter("title"));
    msg.setType(request.getParameter("type"));
    msg.setContent(request.getParameter("content"));

    QString idParam = request.getParameter("id");

    //编辑消息
    if(!idParam.isEmpty())
    {
        int id = idParam.toInt();
        msg.setId(id);
        msg.setUpdateDate(QDateTime::currentDateTime());
        msg.setUpdateName(visitUser.getUserName());

        if(!m_pHelper->updateEntity(&msg))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
        }
    }
    //新增消息
    else
    {
        //保存消息
        msg.setCreateDate(QDateTime::currentDateTime());
        msg.setCreateName(visitUser.getUserName());
        msg.setUpdateDate(QDateTime::currentDateTime());
        msg.setUpdateName(visitUser.getUserName());
        msg.setVersion(1);
        msg.setStatus(QString::number(SysMessage::Status_Draft));

        if(!m_pHelper->insertEntity(&msg))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
        }
    }

    ResponseUtil::replyJson(response, ret);
}

//删除系统消息
void SysMsgController::del(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString idParam = request.getParameter("id");

    if(idParam.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    int id = idParam.toInt();

    SysMessage msg;
    msg.setId(id);
    if(!m_pHelper->deleteEntity(&msg))
    {
        ret.failedMsg(QStringLiteral("操作失败"));
    }

    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::DEL, QStringLiteral("删除系统消息"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("删除系统消息成功"));
    m_pHelper->insertEntity(&log);
}

//发布系统消息
//http://localhost:9004/demo/func/message/sys/publish?id=
//{"code":0,"success":true,"msg":"操作成功","data":null}
//{"code":0,"success":false,"msg":"已经发布的消息，不能再次发布","data":null}
void SysMsgController::publish(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral(""));
    QString idParam = request.getParameter("id");

    if(idParam.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    SysMessage msg;
    msg.setId(idParam.toInt());
    if(!m_pHelper->selectEntityById(&msg))
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    if(msg.getStatus() == QString::number(SysMessage::Status_Publish))
    {
        ret.failedMsg(QStringLiteral("已经发布的消息，不能再次发布"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    msg.setStatus(QString::number(SysMessage::Status_Publish));
    msg.setPublicTime(QDateTime::currentDateTime());
    m_pHelper->updateEntity(&msg);

    QList<SysUser> userList;
    QStringList condi;
    m_pHelper->getUserList(userList, condi, "");
    foreach(SysUser user, userList)
    {
        SysUserMessage umsg;
        umsg.setUserId(user.getId());
        umsg.setSysMessageId(msg.getId());
        umsg.setTitle(msg.getTitle());
        umsg.setContent(msg.getContent());
        umsg.setType(msg.getType());
        umsg.setReadStatus(QString::number(SysUserMessage::Read_No));
        umsg.setDeleteStatus(QString::number(SysUserMessage::Delete_No));
        umsg.setPublicTime(QDateTime::currentDateTime());

        umsg.setCreateDate(QDateTime::currentDateTime());
        umsg.setCreateName(visitUser.getUserName());
        umsg.setUpdateDate(QDateTime::currentDateTime());
        umsg.setUpdateName(visitUser.getUserName());
        umsg.setVersion(1);

        m_pHelper->insertEntity(&umsg);
    }


    ResponseUtil::replyJson(response, ret);
}
